package com.itboye.jinpuyiyuan.utils.sputil;

import android.content.Intent;
import android.util.Log;
import android.widget.ImageView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.itboye.jinpuyiyuan.app.MyApplication;
import com.itboye.jinpuyiyuan.widget.FilterUtil;
import com.itboye.jinpuyiyuan.widget.MultipartRequest;
import com.itboye.jinpuyiyuan.widget.XImageLoader;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;



/**
 * Created by itboye on 2017/3/20.
 */

public class HeadUrl {
    public static  void onImage(String str, final ImageView img) {
        if (str == null) {
            MAlert.alert("请上传正确的图片");
            return;
        }
        File files = new File(str+"");

        Map<String, String> params = new HashMap<String, String>();
//        params.put("uid", IsStringSPUtils.IsUid());
        params.put("type", "avatar");
        MultipartRequest multipartRequest = new MultipartRequest(
                Const.IMAGE_URL,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String arg0) {
                        Log.d("urlTime", arg0.toString());

                        allInfoFromJson(arg0.toString(),img);

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                // TODO Auto-generated method stub
                MAlert.alert(arg0);
            }
        }, "image", files, params);
        MyApplication.addRequest(multipartRequest);

    }
    public static void allInfoFromJson(String jsonStr , ImageView imgHead) {
        try {
            JSONArray jsonArray = new JSONObject(jsonStr).getJSONArray("data");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                String busLine = jsonObject.getString("imgurl");
                String busName = jsonObject.getString("id");
                Log.d("busLin", busName);
                String time = String.valueOf((int) (Math.random() * 10));
//                MAlert.alert("上传成功!");
                SPUtils.put(MyApplication.getInstance(), null,
                        Const.HEAD, busName);
                XImageLoader.load(Const.IMAGE_HEAD + busName+"&random" + time,
                        imgHead);
                // 发送广播更新头像
                Intent intent2 = new Intent(FilterUtil.HEAD);
                MyApplication.getInstance().sendBroadcast(intent2);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}
